package com.cl.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cl.blog.common.Const;
import com.cl.blog.entity.BUserFollow;
import com.cl.blog.mapper.BUserMapper;
import com.cl.blog.service.BUserFollowService;
import com.cl.blog.mapper.BUserFollowMapper;
import com.cl.blog.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * @author object
 * @description 针对表【b_user_follow】的数据库操作Service实现
 * @createDate 2024-03-14 17:13:59
 */
@Service
public class BUserFollowServiceImpl extends ServiceImpl<BUserFollowMapper, BUserFollow>
		implements BUserFollowService {
	@Autowired
	BUserMapper bUserMapper;
	@Autowired
	JwtUtil jwtUtil;

	@Override
	public boolean follow(Integer userId, String token) {
		Claims claim = jwtUtil.getClaimByToken(token, Const.GRADE_USER);
		String currentUserId = claim.getSubject();
		long count = this.count(new QueryWrapper<BUserFollow>()
				.eq("user_id", Integer.valueOf(currentUserId))
				.eq("follow_user_id", userId)
		);
		if (count >= 1) {
			boolean remove = this.remove(new QueryWrapper<BUserFollow>()
					.eq("user_id", Integer.valueOf(currentUserId))
					.eq("follow_user_id", userId));
			if (remove) {
				return false;
			}
		} else {
			BUserFollow bUserFollow = new BUserFollow();
			bUserFollow.setUserId(Integer.valueOf(currentUserId));
			bUserFollow.setFollowUserId(userId);
			bUserFollow.setCreateTime(LocalDateTime.now());
			boolean save = this.save(bUserFollow);
			if (save) {
				return true;
			}
		}

		return false;
	}
}




